/* eslint-disable no-shadow */
import { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { View, Input, ScrollView } from '@tarojs/components'
import { AtButton } from 'taro-ui'
import { getViewByCityCode } from '@/api'
import StorePlatformListView from '@/components/StorePlatformListView'
import classnames from 'classnames'
import map from '@/utils/map'
import { connect } from 'react-redux'
import { updateStore, initLocation } from '@/store/location/action'
import { getCanOrderStoreList, getCanBookingStoreList } from '@/api'
import { getAnnualStoreList } from '@/api/order'

import './index.scss'

interface State {
  address: any
  tabIndex: number
  store: IStore | null
  loadLocation: boolean
  otfenStore: IStore[] | null
  commonlyUsed: []
  nearStore: IStore[] | null
  reload: boolean
  keyWordStore: IStore[]
  allStoreList: IStore[]
  selectStore: object,
  orderNumber: string, // 预约订单号
  keyword: string,
  tipTxt: string
  selectArea: object

}

@connect<any>(({ location, user }) => ({ location, user }), _dispatch => ({
  dispatchStore(params) {
    return _dispatch(updateStore(params))
  },
  dispatchLocation(params) {
    return _dispatch(initLocation(params))
  }
}))
export default class Index extends Component<any> {
  $instance = getCurrentInstance();
  protected __data__: any
  constructor (props) {
    super(props)
    this.state = {
      address: null,
      tabIndex: 2,
      store: null,
      loadLocation: false,
      otfenStore: null,
      commonlyUsed: [],// 常用门店
      nearStore: null,// 附近可下单门店
      reload: false,
      keyWordStore: [],
      keyword: '',
      allStoreList: [],
      selectStore: {},
      orderNumber: '',
      tipTxt: '数据加载中...',
      selectArea: {}
    }
    this.__data__ = process.env.TARO_ENV === 'weapp' ? '__data__' : 'data'
  }
  state: State

  UNSAFE_componentWillMount() { }
  async componentDidMount() {
    console.log('componentDidMount')
    // await this.currStore()
    const { address } = this.props.location
    console.log(' this.props.location', this.props.location)
    let params = {}
    if (address) {
      const { lat: latitude, lng: longitude } = address.location
      params = {
        location: { latitude, longitude }
      }
    }
    console.log('有没有执行--await this.getLocation(params)')
    await this.getLocation(params)
    if (process.env.TARO_ENV === 'weapp') {
      this.getNearStore('tab')
    }

  }
  UNSAFE_componentWillReceiveProps(nextProps, nextContext) {
    const { address } = this.state
    const propsLocation = nextProps.location.address
    if (propsLocation) {
      if (address) {
        if (propsLocation.address !== address.address) {
          this.setState({
            location: propsLocation,
            address: propsLocation
          })
        }
      }
    }
  }
  componentWillUnmount() { }
  async componentDidShow() {
    console.log('componentDidShow')
    console.log('this.$instance.router.params', this.$instance.router.params)
    let { orderNumber = '', cityCode } = this.$instance.router.params
    try {
      if (cityCode) {
        let data = await getViewByCityCode({
          adCode: cityCode
        })
        let city = data.data.data
        this.setState({ selectArea: city })
      }
    } catch {
    }
    this.setState({ orderNumber })
    let pages = Taro.getCurrentPages();
    let currentPage = pages[pages.length - 1]; // 获取当前页面
    if (currentPage[this.__data__].selectArea) { // 获取值
      this.setState({ selectArea: currentPage[this.__data__].selectArea })
      console.log(' currentPage.[this.__data__].selectArea', currentPage[this.__data__].selectArea)
      this.getNearStore('tab')
    }
  }
  componentDidHide() { }
  componentDidCatchError() { }
  componentDidNotFound() { }

  // 当前位置信息
  async getLocation(params?) {
    console.log('会不会执行到这里来----当前位置信息')
    if (process.env.TARO_ENV === 'weapp') { // 微信小程序
      const reverseGeocoder: any = await map.reverseGeocoder(params)
      console.log('reverseGeocoder', reverseGeocoder)
      if (reverseGeocoder) {
        const { dispatchLocation } = this.props
        const address = {
          city: reverseGeocoder.ad_info.city,
          address: reverseGeocoder.address,
          location: reverseGeocoder.location,
          title: reverseGeocoder.formatted_addresses.recommend
        }
        dispatchLocation(address)
        console.log('')
        this.setState({
          reload: true,
          address,
          loadLocation: true
        })
      } else {
        this.setState({
          reload: true,
          loadLocation: true
        })
      }
    } else { // 支付宝小程序定位逻辑
      let _this = this
      my.showLoading()
      my.getLocation({
        type: 2,
        async success(res) {
          my.hideLoading()
          let { latitude, longitude, city, district, streetNumber } = res
          let location = res
          console.log('location', location)
          const { dispatchLocation } = _this.props
          const address = {
            city: city,
            address: `${city}${district}${streetNumber.street}${streetNumber.number}`,
            location: location,
            latAndLng: {
              latitude,
              longitude,
            },
            latitude,
            longitude,
            title: ''
          }
          dispatchLocation(address)
          console.log('_this.props', _this.props.location)
          _this.setState({
            reload: true,
            address,
            loadLocation: true
          }, () => {
            _this.getNearStore('tab')
          })

        },
        async fail(err) {
          _this.setState({
            reload: true,
            loadLocation: true
          }, () => {
            _this.getNearStore('tab')
          })
        }
      })
    }

  }

  // 开启定位
  openSetting() {
    Taro.openSetting().then(res => {
      const status = res.authSetting['scope.userLocation']
      if (status) {
        this.setState({
          reload: false
        })
        this.getLocation()
      }
    })
  }

  // 附近门店数据
  getNearStore(mode?= 'init') {
    const { address } = this.props.location
    let alipayAddress = this.state.address
    console.log('alipayAddress', alipayAddress)
    console.log('getNearStoregetNearStoregetNearStore--address', address)
    let { goodsIds, type, goodsDistributionId, orderNumber = '', couponItemIds, cityCode = '', areaCode = '', annualCardId = '', isTopicAnnualCard = 0, jihuasuanId, jihuasuanSource } = this.$instance.router.params
    let paramsData = {
      goodsIds: goodsIds,
      userLongitude: address && address.location.lng || alipayAddress && alipayAddress.longitude || '',
      userLatitude: address && address.location.lat || alipayAddress && alipayAddress.latitude || '',
      query: {
        page: this.nearStorePage
      },
    }
    console.log('this.$instance.router.params', this.$instance.router.params)
    let { selectArea } = this.state
    if (cityCode) {
      paramsData.cityCode = cityCode
      paramsData.areaCode = areaCode || ''
    }
    // jihuasuanId,
    // jihuasuanSource,
    if (jihuasuanId) {
      paramsData.jihuasuanId = jihuasuanId
      paramsData.jihuasuanSource = jihuasuanSource
    }
    // 如果链接携带分销信息 查询门店时需一起发送
    if (goodsDistributionId) {
      paramsData.query.goodsDistributionId = goodsDistributionId
    }
    if (selectArea.adCode) {
      paramsData.cityCode = selectArea.adCode
      paramsData.areaCode = selectArea.districtCode || ''
    }
    let interfaceType = getCanOrderStoreList
    if (type && type == 'booking') { // 预约门店
      interfaceType = getCanBookingStoreList
      if (orderNumber) {
        paramsData.orderNumber = orderNumber
      }
      if (couponItemIds) {
        paramsData.couponItems = JSON.stringify(couponItemIds.split(','))
      }
    }
    if (type && type == 'annual') { // 年卡可销售门店
      interfaceType = getAnnualStoreList
      if (annualCardId) {
        paramsData.annualCardId = annualCardId
      }
      if (isTopicAnnualCard) {
        paramsData.isTopicAnnualCard = isTopicAnnualCard
      }
      // if(cityCode){
      // 	paramsData.cityCode = cityCode
      // }
    }

    console.log('paramsData', paramsData)
    Taro.showLoading({ title: '正在加载' })
    interfaceType(paramsData).then(res => {
      const data = res.data.data
      const totalPage = Number(res.header['x-pagination-page-count']) || Number(res.header['X-Pagination-Page-Count'])
      if (this.nearStorePage >= totalPage) {
        this.canAddNearStore = false
      }
      let list = []
      let nearStore = []// 附近门店
      if (nearStore) {
        list = [...nearStore, ...data]
      } else {
        list = [...data]
      }
      list.map((val) => {
        nearStore.push(val)
      })
      let tipTxt = '正在加载数据...'
      if (nearStore.length == 0) {
        tipTxt = '暂无可服务门店'
      }
      this.setState({
        nearStore,
        tipTxt
      }, () => {
        Taro.hideLoading()
      })

    }).catch(() => {
      let tipTxt = '暂无可服务门店'
      this.setState({
        nearStore: [],
        tipTxt
      })
    })
  }

  // 当前门店数据
  async currStore() {
    const { storeLocation } = this.props.location
    this.setState({
      store: storeLocation
    })
  }


  // 搜索
  searchLocation = (e) => {
    const { value: keyword } = e.detail
    let { goodsIds, type, goodsDistributionId, orderNumber = '', couponItemIds, isTopicAnnualCard = 0, jihuasuanId, jihuasuanSource } = this.$instance.router.params
    if (keyword) {
      const { address, selectArea } = this.state
      let paramsData = {
        goodsIds: goodsIds,
        userLongitude: address.location.lng,
        userLatitude: address.location.lat,
        query: {
          filter: { or: [{ storeNameKeyword: { klike: keyword } }, { addressKeyword: { like: keyword } }] },
        }
        // query: {}
      }
      if (jihuasuanId) {
        paramsData.jihuasuanId = jihuasuanId
        paramsData.jihuasuanSource = jihuasuanSource
      }
      // 如果链接携带分销信息 查询门店时需一起发送
      let { goodsDistributionId, type, orderNumber, couponItemIds, cityCode, areaCode, annualCardId = '' } = this.$instance.router.params
      console.log('couponItemIds', couponItemIds)
      if (goodsDistributionId) {
        paramsData.query.goodsDistributionId = goodsDistributionId
      }
      if (cityCode) {
        paramsData.cityCode = cityCode
        paramsData.areaCode = areaCode || ''
      }
      if (selectArea.adCode) {
        paramsData.cityCode = selectArea.adCode
        paramsData.areaCode = selectArea.areaCode || ''
      }
      let interfaceType = getCanOrderStoreList
      if (type && type == 'booking' && orderNumber || couponItemIds) { // 预约门店
        interfaceType = getCanBookingStoreList
        if (orderNumber) {
          paramsData.orderNumber = orderNumber
        }
        if (couponItemIds) {
          paramsData.couponItems = JSON.stringify(couponItemIds.split(','))
        }
      }
      if (type && type == 'annual') { // 年卡可销售门店
        interfaceType = getAnnualStoreList
        if (annualCardId) {
          paramsData.annualCardId = annualCardId
        }
        if (isTopicAnnualCard) {
          paramsData.isTopicAnnualCard = isTopicAnnualCard
        }
      }

      Taro.showLoading({ title: '正在加载' })
      console.log('paramsData---paramsData', paramsData)
      interfaceType(paramsData).then(res => {
        const data = res.data.data
        this.setState({
          keyword,
          keyWordStore: data
        }, () => {
          Taro.hideLoading()
        })
      }).catch(() => {
        Taro.hideLoading()
      })
    } else {
      this.setState({
        keyword,
        keyWordStore: []
      }, () => {
        Taro.hideLoading()
      })
    }
  }

  // 切换城市
  gotoSelectArea = () => {
    let { type = '', annualCardId = '', isTopicAnnualCard = 0 } = this.$instance.router.params
    if (type && type == 'annual') { // 只能切换该年卡适用范围内的城市
      Taro.navigateTo({
        url: `/pages/platform/city/index?type=1&method=annual&annualCardId=${annualCardId}&isTopicAnnualCard=${isTopicAnnualCard}`
      })
    } else {
      Taro.navigateTo({
        url: `/pages/platform/city/index?type=1&isTopicAnnualCard=${isTopicAnnualCard}`
      })
    }

  }

  async changeStore(store?) {
    console.log('store: ', store);
    store['topUrl'] = store['logo']
    let pages = Taro.getCurrentPages(); // 获取当前的页面栈
    let prevPage = pages[pages.length - 2]; // 获取上一页面
    const { dispatchStore } = this.props
    await dispatchStore(store)
    prevPage.setData({ //设置上一个页面的值
      selectStore: store
    })
    Taro.navigateBack({
      delta: 1
    })
  }

  private canAddNearStore: boolean = true
  private addNearStoreStatus = false
  private nearStorePage = 1
  async addNearStore(e) {
    if (!this.canAddNearStore) return
    if (!this.addNearStoreStatus) {
      this.nearStorePage++
      this.addNearStoreStatus = true
      await this.getNearStore()
      this.addNearStoreStatus = false
    }
  }
  // 附近门店界面
  nearStoreView() {
    const { address, reload, nearStore, tabIndex, tipTxt, selectArea } = this.state
    return (

      <ScrollView lowerThreshold={120} scrollY onScrollToLower={(e) => {
        this.addNearStore(e)
      }} className={classnames('near-store', tabIndex === 2 && 'show')}
      >
        <View className='sub-title-platform'>
          <View>当前位置</View>
          <View className='platform-city' >
            <View className='choose-city'>{selectArea.name ? selectArea.name : Taro.getStorageSync('CURRENT_LOCATION_INFO').name}</View>
            <View onClick={this.gotoSelectArea}>切换城市</View>
          </View>
        </View>
        {
          address ?
            <View className='current-location'>

              {
                process.env.TARO_ENV === 'weapp' ? (
                  <View className='location-info'>
                    <View className='name'>{address.title}</View>
                    <View className='address'>{address.address}</View>
                  </View>
                ) : <View className='location-info'>
                  <View className='address'>{address.address}</View>
                </View>
              }


            </View> :
            <View className='current-location'>
              <View className='location-info'><View className='name'>暂无位置信息</View></View>
              <AtButton className='reset-location' onClick={() => this.openSetting()} size='small' loading={!reload} type='secondary'>
                {!reload ? '' : '开启定位'}
              </AtButton>
            </View>
        }
        {
          nearStore && nearStore.length > 0 ? (
            <View className='near-list'>
              <View className='sub-title-platform'>可服务门店</View>
              {
                nearStore.map(list => {
                  return <StorePlatformListView handleEvent={this.changeStore.bind(this)} key={list.id} list={list} />
                })
              }
            </View>
          ) : <View className='no-service'>{tipTxt}</View>
        }
      </ScrollView>
    )
  }

  // 搜索门店界面
  keywordStoreView() {
    const { keyWordStore } = this.state
    return (
      keyWordStore.length == 0 ? (
        <View className={classnames('keyword-store-content')}>
          <View className='keyword-center'>暂无搜索到门店！</View>
        </View>
      ) :
        <View className={classnames('keyword-store-content')}>
          {
            keyWordStore.map(list => {
              return <StorePlatformListView handleEvent={this.changeStore.bind(this)} key={list.id} list={list} />
            })
          }
        </View>
    )
  }

  render() {
    const { loadLocation, keyword } = this.state
    const { method } = this.$instance.router.params
    return loadLocation && (
      <View className='store-index'>
        {
          <View className={classnames('store-main', method === 'vendorStore' && 'vendor-store')}>
            <View className='store-index-fixed'>
              <View className='sub-tips'>此商品可在以下门店服务</View>
              <View className='import-keywords'><Input placeholder-class='placeholder' onInput={(e) => this.searchLocation(e)} className='ipt' placeholder='输入门店名称、地址或区域'></Input></View>
            </View>
            {this.nearStoreView()}
            {keyword && this.keywordStoreView()}
          </View>
        }
      </View>
    )
  }
}
